<template>
  <div class="uploadFile">
    <el-dialog
      width="38%"
      :visible.sync="fileUpDialogVisible"
      title="文件上传"
      :close-on-click-modal="false">
     <el-form label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item>
         <el-upload
            class="upload-demo"
            drag
            :action="uploadUrl"
            :auto-upload="false"
            :accept="acceptFile"
            ref="upload"
            :before-upload="fnBeforeUpload"
            :on-remove="fnUploadRemove"
            :on-exceed="fnUploadExceed"
            :on-change="fnUploadChange"
            :http-request="fnUploadRequest"
            :limit = "limit"
            :disabled="disabled"
            :file-list="fileList"
            multiple>
           <i class="el-icon-upload"></i>
           <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
           <a style="color:red;cursor:pointer;" slot="tip" v-if="importTemplateUrl" @click="handleDownloadImportTemplate(importTemplateUrl)">点击此处下载导入模板</a>
           <div class="el-upload__tip" slot="tip" v-if="accept == 'all'">注：请上传图文件，且文件大小不能超过50M</div>
           <div class="el-upload__tip" slot="tip" v-if="accept == 'image'">注：请上传图片格式文件，且文件大小不能超过20M</div>
           <div class="el-upload__tip" slot="tip" v-if="accept == 'pdf'">注：请上传PDF格式文件，且文件大小不能超过20M</div>
           <div class="el-upload__tip" slot="tip" v-if="accept == 'video'">注：请上传mp4/m2v/mkv格式文件，且文件大小不能超过50M</div>
           <div class="el-upload__tip" slot="tip" v-if="accept == 'excel'">注：请上传EXCEL格式文件，且文件大小不能超过50M</div>
           <div class="el-upload__tip" slot="tip" v-if="accept == 'image,pdf'">注：请上传图片、PDF格式文件，且文件大小不能超过20M</div>
           <!--<div class="el-upload-tip" slot="tip">
             <ul style="margin-top: 10px;">
               <li>1、目前仅支持PDF格式文件上传</li>
               <li>2、至少上传一个，最多上传10个文件</li>
               <li>3、每个文件大小不能超过20M</li>
             </ul>
           </div>-->
          </el-upload>

        </el-form-item>
      </el-form>
        <slot name="tip">123123123</slot>
        <div slot="footer" class="dialog-footer">
          <el-button @click="fileUpDialogVisible=false">取消</el-button>
          <el-button @click="sureUpload" :loading="submitLoading" type="primary">确定上传</el-button>
       </div>
    </el-dialog>
  </div>
</template>
<script>
import * as Constants from "@/constants/constants";
import ComponentApi from "@/api/components/component";

export default {
  name: 'uploadFile',
  props: {
    folder: { // 上传至OSS的文件夹路径
      type: String,
      default: 'all'
    },
    limit: {
      type: Number,
      default: 10
    },
    accept: {  // all,image,pdf,video,excel
      type: String,
      required: true
    },
    importTemplateUrl:{
      type:String,
    }
  },
  data() {
    return {
      ossClient: null,
      uploadUrl: '',
      fileList: [],
      uploadHeaders: {
        authorization: ''
      },
      uploadFileList: [],
      chooseFileLength: 0,
      fileUpDialogVisible: false,
      submitLoading: false,
      acceptFile: '',
      acceptFileType: '',
      disabled: false
    }
  },
  watch: {
    accept(value) {
      if (value === 'image'){
        this.acceptFile = '.png,.jpg,.jpeg,.bmp'
      }else if(value === 'pdf'){
        this.acceptFile = '.pdf'
      }else if(value === 'video'){
        this.acceptFile = '.mp4,.m2v,.mkv'
      }else if(value === 'excel'){
        this.acceptFile = '.xls,.xlsx'
      }else if(value === 'image,pdf'){
        this.acceptFile = '.png,.jpg,.jpeg,.bmp,.pdf'
      }
    }
  },
  methods: {
    async fnUploadRequest (option) {
      //console.log("---begin loading---")
      try {
        const _this = this
        // 判断已经上传过的不处理--情景：先上传成功3个，后补充1个，之前3个会循环调用。
        if (option && option.response && option.response.url) {
          return
        }

        // 当前上传的文件
        let file = option.file
        const fileName = file.name
        const fileType = fileName.split("\.")[1];
        /*let fileTempName = _this.$Utils.mathRand() + fileName.split("\.")[0];
        if (fileTempName.length > 12){
          fileTempName = fileTempName.substring(0,12);
        }*/
        const newName = _this.$Utils.mathRand19() +"."+ fileType;
        const storeAs = Constants.OSS_WEB_URL + _this.folder + '/' + newName;
        //console.log('开始上传，文件名>>>>>' + fileName)
        // TODO 测试 注释上传动作
        _this.ossClient.put(storeAs, file, {}).then(
          function (ret) {
            if (ret.res.statusCode === 200) {
              let realUrl = ret.url.replace(Constants.OSS_URL,Constants.OSS_REAL_URL);
              ret.url = realUrl;

              _this.uploadFileList.push(realUrl)
              //console.log('上传成功，文件名>>>>>' + fileName)
              //console.log('上传成功，_this.uploadFileList>>>>>' + _this.uploadFileList)
              //option.onSuccess(ret)
              // 值回传
              option.response = ret
              return ret
            } else {
              option.onError('上传失败')
            }
          }
        ).catch(function (err) {
          console.error(err)
        })
      } catch (error) {
        console.error(error)
        this.disabled = false
        option.onError('上传失败')
        this.$error(error.message)
      }
    },
    /*async fnUploadSuccess (response, file, fileLists) {
      // 会执行两次，第一次是因为获取oss token执行了http请求，成功返回会引起这个方法被执行，所以添加这个判断
      if (typeof(response) == "undefined"){
        return;
      }
      /!*console.log('file>>>>' + JSON.stringify(file));
      console.log('response>>>>' + JSON.stringify(response));
      console.log('fileLists>>>>' + JSON.stringify(fileLists));*!/
      let _this = this
      _this.uploadFileList.push(response.url)
      console.log('上传成功_this.uploadFileList>>>>>>' + _this.uploadFileList)
    },*/
    fnUploadChange (file, fileList) {
      //文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
      //console.log(fileList+"选中文件后--"+file)
      //console.log("选中文件后，文件长度--"+fileList.length)
      this.chooseFileLength = fileList.length
    },
    fnUploadRemove (file, fileList) {
      //文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
      //console.log(fileList+"移除的文件--"+file)
      //console.log("移除文件后，文件长度--"+fileList.length)
      this.chooseFileLength = fileList.length
    },
    /**
     * el-upload
     * on-exceed	文件超出个数限制时的钩子
     *  */
    fnUploadExceed (files, fileList) {
      let _this = this
      _this.$message.warning(`最多可上传 ${_this.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      //_this.$message.warning(`当前限制最多上传 ${_this.files} 个文件!`)
    },
    /**
     * el-upload
     * on-before	文件上传前限制时的钩子
     *  */
    fnBeforeUpload (file) {
      let _this = this
      if (_this.accept != 'all'){
        const result = _this.$Utils.matchType(file.name);
        if (_this.accept.indexOf(result) == -1) {
          _this.$message.error('文件格式不支持!');
          _this.submitLoading = false
          return false;
        }
        let size = 20
        if (_this.accept == 'video' || _this.accept == 'excel'){
          size = 50
        }
        const isLt2M = file.size / 1024 / 1024 < size;
        if (!isLt2M) {
          _this.$message.error(`文件大小不能超过 ${size}MB!`)
          _this.submitLoading = false
          return false;
        }
      }
      return true;
    },
    sureUpload() {
      let _this = this
      // 判断是否有选择文件
      if (_this.chooseFileLength == 0){
        _this.$message.error('您未选择需上传的文件!')
        return
      }
      _this.submitLoading = true
      // 请求oss，获取授权
      ComponentApi.uploadOss().then(async res => {
        _this.ossClient = (await import('ali-oss')).default({
          region: Constants.OSS_REGION,
          accessKeyId: res.data.accessKeyId,
          accessKeySecret: res.data.accessKeySecret,
          stsToken: res.data.securityToken,
          bucket: Constants.OSS_BUCKET
        })

        _this.$refs.upload.submit()
        const interval = setInterval(() => {
          // 根据上传个数相等，判断是否已上传完毕
          if (_this.uploadFileList.length>0 && _this.uploadFileList.length === _this.chooseFileLength){
            _this.fileUpDialogVisible = false
            // 使用$emit出发父组件的自定义事件
            _this.$emit('uploadFileList', this.uploadFileList)
            //console.log(666,JSON.stringify(this.uploadFileList))
            _this.submitLoading = false
            clearInterval(interval);
          }
        }, 1000)
      });

    },
    handleCreate() {
      // 清空旧文件 - 上一次弹窗上传过的文件
      this.fileList = []
      this.uploadFileList = []
      this.fileUpDialogVisible = true
    },
    handleDownloadImportTemplate(url){
      // 下载导入模板
      window.open(url, "location=no");
    }
  }
}
</script>
<style>
</style>
